package com.gao.api.gate.quick.proto.filter;

import com.gao.api.gate.quick.common.util.AssertUtil;
import com.gao.api.gate.quick.proto.http.HttpRequestContext;

import java.util.concurrent.ExecutorService;
import java.util.function.Predicate;

/**
 * <p></p>
 *
 * @author gaoshuangwen
 * @since 2022/01/07 14:28
 */
public abstract class AbstractFilter implements Filter {

    public static final String GLOBAL_GROUP_FILTER ="global";

    private FilterDefinition filterDefinition;

    private ExecutorService executorService;

    public AbstractFilter(FilterType filterType) {
        AssertUtil.isNull(filterType,"filterType is null");
        // 构建默认的FilterDefinition
        FilterDefinition definition = new FilterDefinition();
        definition.setFilterGroup(AbstractFilter.GLOBAL_GROUP_FILTER);
        definition.setFilterName(this.getClass().getSimpleName());
        this.filterDefinition = definition;
    }

    public AbstractFilter(FilterDefinition filterDefinition) {
        AssertUtil.isNull(filterDefinition,"filterDefinition is null");
        this.filterDefinition = filterDefinition;
    }


    // TODO: 2022/1/7 监控组件
    @Override
    public void filter(HttpRequestContext context) throws FilterException {
        // 不支持的filter,直接返回
        if (this.filterDefinition.isDisabled() || should(context)){
            return;
        }
        doFilter(context);
    }

    public abstract void doFilter(HttpRequestContext context) throws FilterException;

    @Override
    public boolean should(HttpRequestContext context){
        Predicate<HttpRequestContext> shouldPredicate = filterDefinition.getShouldPredicate();
        return shouldPredicate == null || shouldPredicate.test(context);
    }

    @Override
    public int order() {
        return filterDefinition.getOrder();
    }

    @Override
    public boolean sync(){
        return filterDefinition.isSync();
    }

    @Override
    public boolean disable(){
        return filterDefinition.isDisabled();
    }
    @Override
    public FilterDefinition getFilterDefinition() {
        return filterDefinition;
    }
    @Override
    public FilterType getFilterType() {
        return filterDefinition.getFilterType();
    }

}
